<template>
  <div>
    <el-form label-position="top" :model="entity" :rules="rules">
      <el-form-item label="标题：" prop="title">
        <el-input v-model="entity.title" placeholder="请输入标题" style="width: 1065px"></el-input>
      </el-form-item>
      <el-form-item label="简介：" prop="description">
        <el-input v-model="entity.description" placeholder="请输入简介" style="width: 1065px"></el-input>
      </el-form-item>
      <el-form-item label="内容：" prop="content" style="width: 1120px">
        <QuillEditor ref="quill-editor" v-model:content="entity.content" :options="editorOption" contentType="html"
                     style="margin-bottom: 5px;"/>
      </el-form-item>
      <el-form-item label="合集：" prop="collectionId">
        <el-space>
          <el-select v-model="entity.collectionId" placeholder="请选择合集" style="width: 200px">
            <el-option v-for="item in collectionList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button type="text" @click="handleDialogVisible">添加新合集</el-button>
        </el-space>
      </el-form-item>
    </el-form>
    <div>
      <span>预览:</span>
    </div>
    <el-card style="margin-top: 10px" shadow="hover">
      <h1 v-html="this.entity.title?this.entity.title:'标题'">
      </h1>
      <p v-html="this.entity.description?this.entity.description:'简介'">
      </p>
      <el-space>
        <span>作者:{{ user.nickname }}</span>
        <span>合集:{{
            this.entity.collectionId ? this.collectionList.find(item => item.id === this.entity.collectionId).name : '无'
          }}</span>
        <span>发布时间:{{ formattedTime }}</span>
      </el-space>
      <el-divider/>
      <div v-html="this.entity.content?this.entity.content:'正文'">
      </div>
    </el-card>
    <div style="justify-content: center;display: flex;align-items: center;margin-top: 10px">
      <el-button @click="()=>this.$router.push('/work')" v-if="entity.publishStatus==='已发布'">取消</el-button>
      <el-button @click="draft" v-else>草稿</el-button>
      <el-button type="primary" @click="submit">发布</el-button>
    </div>
    <el-dialog v-model="dialogVisible" title="添加合集" width="400px" center>
      <el-form :model="collection" :rules="collectionRules">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="collection.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-button type="primary" @click="addCollection" style="margin-left: 90px;width: 180px">添加</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
// 工具栏配置
import request from "@/utils/request.js";

const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  ["blockquote", "code-block"], // 引用
  [{list: 'ordered'}, {list: 'bullet'}], // 有序、无序列表
  [{script: "sub"}, {script: "super"}], // 上标/下标
  [{indent: '-1'}, {indent: '+1'}], // 缩进
  [{direction: 'rtl'}], // 文本方向
  [{size: ['small', false, 'large', 'huge']}], // 字体大小
  [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
  [{color: []}, {background: []}], // 字体颜色、字体背景颜色
  [{font: []}], // 字体种类
  [{align: []}], // 对齐方式
  ['clean'], // 清除文本格式
  ['link', 'image', 'video'] // 链接、图片、视频
]
import {QuillEditor, Quill} from '@vueup/vue-quill'
import {container, ImageExtend, QuillWatch} from 'quill-image-extend-module'
import quillTool from '@/utils/quillTool'

Quill.register(quillTool, true)
Quill.register('modules/ImageExtend', ImageExtend)
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import moment from "moment";

export default {
  name: 'EditDictDialog',
  components: {QuillEditor},
  data() {
    return {
      formattedTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      user: JSON.parse(localStorage.getItem('user')),
      collection: {},
      collectionRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在100个字符以内', trigger: 'blur'}
        ]
      },
      dialogVisible: false,
      collectionList: [{}],
      entity: {
        title: null,
        content: null
      },
      submitLoading: false,
      dialogTableVisible: false,
      titleMap: {
        'create': "新增",
        'update': "修改"
      },
      titleStatus: 'create',
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在100个字符以内', trigger: 'blur'}
        ]
      },
      isDisabledName: false,
      editorOption: {
        theme: 'snow',
        placeholder: '请输入正文...',
        modules: {
          // 处理点击工具栏图片按钮，上传图片base64位转换成服务器图片url
          ImageExtend: {
            loading: true, // 可选参数 是否显示上传进度和提示语
            name: 'file', // 参数名
            action: 'http://localhost:8080/file/upload', // 服务器地址，如果为空则采用base64插入图片
            // headers: xhr => { // 设置请求头参数（选填）
            //   xhr.setRequestHeader('Content-Type', 'multipart/form-data')
            // },
            response: res => {
              return res.data
            },
            size: 8, // 可选参数 图片大小,图片不能超过8M
            sizeError: () => {
              this.$message.error('粘贴图片大小不能超过8MB!')
            },

          },
          toolbar: {
            container: toolbarOptions,
            handlers: {
              image: function (value) {
                QuillWatch.emit(this.quill.id)
              },
              link: function (value) {
                if (value) {
                  var href = prompt('请输入链接地址：')
                  this.quill.format('link', href)
                } else {
                  this.quill.format('link', false)
                }
              },
              video: function (value) {
                if (value) {
                  var href = prompt('请输入视频链接：')
                  this.quill.format('video', href)
                } else {
                  this.quill.format('video', false)
                }
              }
            }
          },

        }
      }
    }
  },
  methods: {
    addCollection() {
      request.post('/cc', this.collection).then(res => {
        if (res.code === '0') {
          this.$message.success('添加成功')
          this.getCollectionList();
          this.dialogVisible = false
        }
      })
    },
    handleDialogVisible() {
      this.dialogVisible = true
    },
    draft() {
      this.entity.authorId = this.user.id
      this.entity.authorName = this.user.nickname
      this.entity.publishStatus = '草稿'
      request.post('/article/draft', this.entity).then(res => {
        if (res.code === '0') {
          this.$message.success('保存成功')
          this.$router.push('/work')
        }
      })
    },
    submit() {
      if (this.entity.title === null || this.entity.title === '') {
        this.$message.error('请输入标题')
        return
      }
      if (this.entity.content === null || this.entity.content === '') {
        this.$message.error('请输入正文')
        return
      }
      if (this.titleStatus === 'create') {
        this.entity.authorId = this.user.id
        this.entity.authorName = this.user.nickname
        request.post('/article', this.entity).then(res => {
          if (res.code === '0') {
            this.$message.success('发布成功')
            this.$router.push('/work')
          }
        })
      } else {
        request.put('/article', this.entity).then(res => {
          if (res.code === '0') {
            this.$message.success('修改成功')
            this.$router.push('/work')
          }
        })
      }
      console.log(this.entity)
    },
    getCollectionList() {
      request.get('/cc').then(res => {
        this.collectionList = res.data
      })
    },
    getArticle(id) {
      request.get("/article/" + id).then(res => {
        if (res.code === '0') {
          this.entity = res.data
          this.$nextTick(() => {
            this.$refs['quill-editor'].setHTML(this.entity.content)
          })
        } else {
          this.$message.error(res.msg)
        }
      })
    },
  },
  created() {
    this.getCollectionList();
    if (localStorage.getItem("articleId")) {
      this.getArticle(localStorage.getItem("articleId"));
    }
    if (localStorage.getItem("status")) {
      this.titleStatus = localStorage.getItem("status");
    }
  },
}
</script>
<style scoped>
/deep/ .el-form-item__error {
  margin-top: 10px;
}

/deep/ .el-form-item__content {
  display: inline
}

/deep/ .el-dialog__footer {
  margin-top: 10px;
}

/deep/ .ql-container {
  height: 300px;
  line-height: normal;
  width: auto;
}

/deep/ span.ql-size {
  max-width: 80px !important;
}

/deep/ .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}

/deep/ .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

/deep/ .ql-tooltip[data-mode="video"] {
  left: 0 !important;
}

/deep/ .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

/deep/ .ql-picker.ql-size .ql-picker-label::before,
.ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}

/deep/ .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}

/deep/ .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}

/deep/ .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

/deep/ .ql-picker.ql-header .ql-picker-label::before,
.ql-picker.ql-header .ql-picker-item::before {
  content: "标题";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}

/deep/ .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

/deep/ .ql-picker.ql-font .ql-picker-label::before,
.ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}

/deep/ .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}

/deep/ .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}

img {
  max-width: 40%;
  height: auto;
}
</style>